#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include <netinet/ip.h>
#include <string.h>
#include <string>
#include "log.hpp"

class Tcpclient{
public:
    Tcpclient(uint16_t port,std::string ip)
    :port_(port)
    ,ip_(ip)
    ,sockfd_(-1)
    {
        sockfd_ = socket(AF_INET,SOCK_STREAM,0);
        if(sockfd_ < 0)
        {
            log(FATAL,"client create socket err");
            exit(-1);
        }
        // 由操作系统来完成bind
        struct sockaddr_in local;
        bzero(&local,sizeof(local));
        local.sin_addr.s_addr = inet_addr(ip_.c_str());
        local.sin_family = AF_INET;
        local.sin_port = htons(port_);
        if(connect(sockfd_,(const struct sockaddr*)&local,sizeof(local)) < 0)
        {
            log(FATAL,"connect to server err");
            exit(-1);
        }
    }

    void start()
    {
        while(true)
        {
            std::cout<<"echo# ";
            std::string buffer;
            getline(std::cin,buffer);
            if(buffer == "exit")
            {
                break;
            }
            write(sockfd_,buffer.c_str(),buffer.size());
        }
    }
    ~Tcpclient()
    {
        log(DEBUG,"close");
        close(sockfd_);
    }
private:
int sockfd_;
uint16_t port_;
std::string ip_;
};
int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        log(FATAL,"Usage:%s port:ip");
    }
    Tcpclient client(atoi(argv[1]),argv[2]);
    client.start();
    return 0;
}